package filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class FilterIp implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//        1、获取请求的ip地址
        String ipAddr = servletRequest.getRemoteAddr();
        System.out.println(ipAddr);
//        2、判断ip地址是否符合要求
        if("127.0.0.1".equals(ipAddr)){
//            强制转换
            HttpServletResponse response = (HttpServletResponse)servletResponse;
            HttpServletRequest request = (HttpServletRequest)servletRequest;

//            获取根目录
            String path = request.getContextPath();

            response.sendRedirect(path+"/filter/error.jsp");
        }else{
            filterChain.doFilter(servletRequest,servletResponse);
        }


    }


    @Override
    public void destroy() {

    }
}
